#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")

void InitWinsock()
{
	WSADATA wsaData;
	int wsOk = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (wsOk != 0)
	{
		printf("Can't Initialize winsock! Quitting\n");
		return;
	}
	printf("Initialize winsock.\n");
}

int main(int argc, wchar_t* argv[])
{
	SOCKET socketS;

	InitWinsock();
	struct sockaddr_in local;
	struct sockaddr_in from;
	int fromlen = sizeof(from);
	local.sin_family = AF_INET;
	local.sin_port = htons(8087);
	local.sin_addr.s_addr = INADDR_ANY;

	// SOCK_STREAM use for TCP and SOCK_DGRAM for UDP
	socketS = socket(AF_INET, SOCK_DGRAM, 0);
	if (socketS == INVALID_SOCKET)
	{
		printf("Can't create a socket! Quitting\n");
		return -1;
	}
	printf("Socket  Created.\n");

	int iBindResult = bind(socketS, (sockaddr*)&local, sizeof(local));
	if (iBindResult == SOCKET_ERROR) {
		printf("bind failed with error: %d\n", WSAGetLastError());
		//freeaddrinfo(result);
		closesocket(socketS);
		WSACleanup();
		return 1;
	}


	while (1)
	{
		char buffer[50],buffer1[50];
		ZeroMemory(buffer, sizeof(buffer));
		printf("Waiting...\n");
		int length = recvfrom(socketS, buffer, sizeof(buffer), 0, (sockaddr*)&from, &fromlen);
		if (length != SOCKET_ERROR)
		{

			buffer[fromlen] = 0;
			printf("Received message from %s: %s\n", inet_ntoa(from.sin_addr), buffer);
			for (int i = 0;; i++) {
				if (buffer[i] == 0)break;
				buffer[i] = buffer[i] + 1;
			}
			sendto(socketS, buffer, sizeof(buffer), 0, (sockaddr*)&from, fromlen);
		}
		//Sleep(500);
	}
	closesocket(socketS);
	return 0;
}
